const FORMAT = require('../../api/util.js')
import API from '../../api/api.js'
import Dialog from '../../lib/vant-weapp/dialog/dialog';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mode: "",
    readOnly: false,
    placeholder: '回复内容时，只支持文字回复，不支持图片以及文字格式等',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    commentNeiRong: "",

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '添加评论'
    })
    if ('mode' in options) {
      this.data.mode = options.mode
    }
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    that.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {}
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {}
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },

  onFocus: function (e) {

  },
  onInput: function (e) {
    this.data.commentNeiRong = e.detail.text
    this.setData({
      neiRong: e.detail.html
    })
  },
  onBlur: function (e) {},

  onFaBu: async function (e) {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo == "") {
      wx.showToast({
        title: '用户信息丢失，请重新登录。',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '正在检测内容。',
      icon: "none",
      mask: true
    })
    await API.checkWenZhiNeiRong(this.data.neiRong).then(res => {
      if (res.result.errCode === 87014) {
        wx.showToast({
          title: '您的文章内有违规内容，请更换图片，请谅解。',
          icon: "none"
        })
        wx.hideLoading()
        return
      }
      wx.hideLoading()

      if (this.data.mode == "comment") {
        Dialog.confirm({
            title: '添加评论',
            message: '请确定是否发表评论',
          })
          .then(() => {
            let currWenZhangComment = wx.getStorageSync('currWenZhangComment')
            if (this.data.commentNeiRong == "") {
              wx.showToast({
                title: '发送内容不能为空。',
                icon: 'none'
              })
              return
            }
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            let commentData = currWenZhangComment.pinLun
            let comment = {
              biMing: userInfo.biMing,
              openid: userInfo._openid,
              pinLunNeiRong: this.data.commentNeiRong,
              pinLunShiJiang: FORMAT.formatDay(Math.floor(new Date().getTime() / 1000)),
              touXiangUrl: userInfo.touXiang
            }
            commentData.unshift(comment)
            API.updatePinLun(currWenZhangComment._id, commentData).then(res => {
              wx.hideLoading()
              wx.removeStorageSync('currWenZhangComment')
              currWenZhangComment.pinLun = commentData
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2]; //上一个页面
              prevPage.setData({
                data: currWenZhangComment
              })
              wx.navigateBack({
                delta: 1
              })
            })
          })
          .catch(() => {
            wx.showToast({
              title: '已经取消发表评论。',
              icon: 'none'
            })
          })
      }
      if (this.data.mode == "huaticomment") {
        Dialog.confirm({
            title: '添加评论',
            message: '请确定是否发表评论',
          })
          .then(() => {
            if (this.data.commentNeiRong == "") {
              wx.showToast({
                title: '发送内容不能为空。',
                icon: 'none'
              })
              return
            }
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            let currHuaTi = wx.getStorageSync('currHuaTi')
            let commentData = currHuaTi.pinLun
            let comment = {
              biMing: userInfo.biMing,
              openid: userInfo._openid,
              pinLunNeiRong: this.data.commentNeiRong,
              pinLunShiJiang: FORMAT.formatDay(Math.floor(new Date().getTime() / 1000)),
              touXiangUrl: userInfo.touXiang
            }
            commentData.unshift(comment)
            API.updateHuaTiPinLun(currHuaTi._id, commentData).then(res => {

              currHuaTi.pinLun = commentData
              let arr = []
              arr.push(currHuaTi)
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2]; //上一个页面
              prevPage.setData({
                huatiList: arr
              })
              wx.setStorageSync('newHuaTi', arr)
              wx.removeStorageSync('currHuaTi')
              wx.hideLoading()
              wx.navigateBack({
                delta: 1
              })

            })
          })
          .catch(() => {
            wx.showToast({
              title: '已经取消发表评论。',
              icon: 'none'
            })
          })
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let shareimages = app.globalData.shareimages
    let index = Math.floor(Math.random() * 5)
    return {
      title: '一个真正匿名的心情小程序',
      imageUrl: shareimages[index],
      path: '/pages/index/index'
    }
  },
  onShareTimeline: function () {
let shareimages = app.globalData.shareimages
    let index = Math.floor(Math.random() * 5)
    return {
      title: '一个真正匿名的心情小程序',
      imageUrl: shareimages[index]
    }
  }
})